package com.flycms.module.agent.schedule;

import com.flycms.module.agent.UserAgentUtils;
import com.flycms.module.agent.VisitPersonRowMapper;
import com.flycms.module.agent.VisitPersonVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author huangzt
 * @version 1.0
 * @date 2020/3/1 19:13
 */
@Component
//@Configuration
//@EnableScheduling
public class FissionWantedTask {

    private final static Logger logger = LoggerFactory.getLogger(FissionWantedTask.class);
    private static Integer logSum = 0;

    //@Scheduled(cron = "0 0/5 * * * ?")
    private void taskEndFissionWanted() {
        JdbcTemplate jdbcTemplate = UserAgentUtils.jdbcTemplate;
        /**
         * 统计属性（访客量，访问量，ip总量，新增访客）
         */
        ConcurrentHashMap<String, Long> visitViewMap = UserAgentUtils.visitViewMap;
        long unique_visitor = visitViewMap.get("unique_visitor");
        long new_unique_visitor = visitViewMap.get("new_unique_visitor");
        long page_view = visitViewMap.get("page_view");
        long solutionVisitor = UserAgentUtils.solutionCount.longValue();
        //更新访客数
        String sql = "update fly_visit set unique_visitor=" + unique_visitor
                + " , new_unique_visitor="+new_unique_visitor + " , page_view="+page_view
                + ",solution_visitor=" + solutionVisitor;
        jdbcTemplate.update(sql);
        if(logSum%360==0){
            logger.info(logSum + "<----定时更新访客数据成功---->");
        }
        //查出原本的访客属性，再做更新
        String sql3 = "select * from fly_visit_person";
        List<VisitPersonVo> visitors = jdbcTemplate.query(sql3, new VisitPersonRowMapper());
        ConcurrentHashMap<String, Date> oldVisitorMap = visitors.stream().collect(Collectors.toMap(
                a -> a.getAgent() + "##" + a.getIp(), VisitPersonVo::getTime,
                (oldVal, currVal) -> currVal, ConcurrentHashMap::new));
        ConcurrentHashMap<String, Date> newVisitorMap = UserAgentUtils.visitorMap;
        for (Object o : newVisitorMap.keySet()) {
            boolean contain;
            contain = oldVisitorMap.containsKey(o);
            if (contain) {
                contain = newVisitorMap.get(o).equals(oldVisitorMap.get(o));
                if (!contain) {
                    Date newDate = newVisitorMap.get(o);
                    String key = String.valueOf(o);
                    String agent = key.split("##")[0];
                    String ip = key.split("##")[1];
                    String sql4 = "update fly_visit_person set time = ? where ip = ? and agent = ?";
                    jdbcTemplate.update(sql4, newDate, ip, agent);
                }
            }else{
                Date newDate = newVisitorMap.get(o);
                String key = String.valueOf(o);
                String agent = key.split("##")[0];
                String ip = key.split("##")[1];
                String sql4 = "insert into fly_visit_person(time,ip,agent) values (?,?,?)";
                jdbcTemplate.update(sql4, newDate, ip, agent);
            }
        }
        //更新总ip量
        String sql6 = "select count(DISTINCT(ip)) from  fly_visit_person";
        long ipCount = jdbcTemplate.queryForObject(sql6, Long.class);
        visitViewMap.put("ip_count",ipCount);
        logSum++;
    }
}
